// API
import { login } from '../../api/user/index.js'
import { getWxConfig } from '../../api/index.js'

// Utils
import { toast } from '../../utils/native'
// #ifdef H5
const jWeixin = require('jweixin-module')
// #endif

const state = {
	// 用户信息
	userInfo: {
		avatar: 'https://apiserver/upload/user.png',
		nickname: '',
		email: ''
	},
};

const getters = {};

const mutations = {
	/**
	 * 设置用户信息
	 * @param {Object} state
	 * @param {Object} data
	 */
	setUserInfo(state, data) {
		state.userInfo = data
	},

};

const onLogin = (code, commit, resolve, method = "smallApp") => {
	login(code, method).then((data) => {
		uni.setStorageSync('token', data
			.token)
		uni.setStorageSync('tokenTime', new Date().getTime())
		if (!data.userInfo.avatar) {
			data.userInfo.avatar =
				'https://apiserver/upload/user.png'
		}
		commit('setUserInfo', data.userInfo)
		resolve()
	})
}

function queryStringToObject(queryString) {
	let obj = {};
	// 去掉开头的问号
	queryString = queryString.slice(1);
	// 分割字符串并遍历
	queryString.split('&').forEach(function(item) {
		let parts = item.split('=');
		obj[parts[0]] = parts[1];
	});
	return obj;
}

const actions = {
	/**
	 * 登录
	 */
	login({
		commit,
		state
	}, callback) {
		return new Promise(resolve => {
			let query = {}
			if (!Object.keys(state.userInfo).length || !uni.getStorageSync(
					'token')) {
				// #ifdef H5
				query = queryStringToObject(window.location.search)
				// #endif
				if (query.code) {
					onLogin(query.code, commit, resolve, 'h5')
				} else {
					uni.showModal({
						title: '温馨提示',
						content: '授权登录',
						success: (res) => {
							if (res.confirm) {
								// #ifdef H5
								toast('1')
								console.log(
									`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx64086f6785cd343b&redirect_uri=${encodeURI(window.location.href)}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
								)
								window.location.href =
									`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx64086f6785cd343b&redirect_uri=${window.location.href}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`

								// #endif
								// #ifdef MP-WEIXIN
								uni.login({
									provider: 'weixin',
									success: (e) => {
										console.log(e)
										onLogin(e.code, commit, resolve)
									},
								})
								// #endif
							} else if (res.cancel) {
								callback && callback()
							}

						}
					})
				}

			} else {
				resolve()
			}
		})
	},
};

export default {
	namespaced: true,
	state,
	getters,
	mutations,
	actions
};